import request from '../utils/request'
import errorHandler from '../utils/errorHandler'
import Taro from '@tarojs/taro'

// API 基础类
class BaseApi {
  constructor(baseUrl = '') {
    this.baseUrl = baseUrl
  }

  // 统一错误处理
  handleError(error, context) {
    return errorHandler.handle(error, context)
  }

  // 带缓存的GET请求
  async getCached(url, params = {}, cacheTime = 5 * 60 * 1000) {
    const cacheKey = `api_cache_${url}_${JSON.stringify(params)}`
    
    try {
      const cached = Taro.getStorageSync(cacheKey)
      if (cached && Date.now() - cached.timestamp < cacheTime) {
        console.log('使用缓存数据:', url)
        return cached.data
      }
    } catch (e) {
      console.warn('读取缓存失败:', e)
    }

    try {
      const data = await request.get(this.baseUrl + url, params)
      
      // 缓存数据
      try {
        Taro.setStorageSync(cacheKey, {
          data,
          timestamp: Date.now()
        })
      } catch (e) {
        console.warn('缓存数据失败:', e)
      }
      
      return data
    } catch (error) {
      throw this.handleError(error, { api: url, params })
    }
  }
}

// 用户相关接口
export const userApi = {
  // 获取用户信息
  async getUserInfo() {
    try {
      return await request.get('/api/user/info')
    } catch (error) {
      throw errorHandler.handle(error, { api: 'getUserInfo' })
    }
  },

  // 更新用户信息
  async updateUserInfo(data) {
    try {
      return await request.put('/api/user/info', data)
    } catch (error) {
      throw errorHandler.handle(error, { api: 'updateUserInfo', data })
    }
  },

  // 用户登录
  async login(loginData) {
    try {
      const result = await request.post('/api/user/login', loginData)
      
      // 登录成功后保存token
      if (result.token) {
        Taro.setStorageSync('token', result.token)
        Taro.setStorageSync('userInfo', result.userInfo)
      }
      
      return result
    } catch (error) {
      throw errorHandler.handle(error, { api: 'login' })
    }
  },

  // 用户登出
  async logout() {
    try {
      await request.post('/api/user/logout')
    } catch (error) {
      console.warn('登出接口调用失败:', error)
    } finally {
      // 无论接口是否成功，都清除本地数据
      Taro.removeStorageSync('token')
      Taro.removeStorageSync('userInfo')
      request.clearQueue()
    }
  }
}

// 订单相关接口
export const orderApi = {
  // 获取订单列表
  async getOrderList(params = {}) {
    try {
      return await request.get('/api/orders', params)
    } catch (error) {
      throw errorHandler.handle(error, { api: 'getOrderList', params })
    }
  },

  // 获取订单详情
  async getOrderDetail(orderId) {
    try {
      return await request.get(`/api/orders/${orderId}`)
    } catch (error) {
      throw errorHandler.handle(error, { api: 'getOrderDetail', orderId })
    }
  },

  // 创建订单
  async createOrder(data) {
    try {
      // 参数验证
      if (!data.serviceType || !data.serviceTime || !data.address) {
        throw new Error('订单信息不完整')
      }
      
      return await request.post('/api/orders', data)
    } catch (error) {
      throw errorHandler.handle(error, { api: 'createOrder', data })
    }
  },

  // 取消订单
  async cancelOrder(orderId, reason = '') {
    try {
      return await request.put(`/api/orders/${orderId}/cancel`, { reason })
    } catch (error) {
      throw errorHandler.handle(error, { api: 'cancelOrder', orderId, reason })
    }
  },

  // 确认订单
  async confirmOrder(orderId) {
    try {
      return await request.put(`/api/orders/${orderId}/confirm`)
    } catch (error) {
      throw errorHandler.handle(error, { api: 'confirmOrder', orderId })
    }
  },

  // 订单评价
  async rateOrder(orderId, rating) {
    try {
      return await request.post(`/api/orders/${orderId}/rate`, rating)
    } catch (error) {
      throw errorHandler.handle(error, { api: 'rateOrder', orderId, rating })
    }
  }
}

// 服务相关接口
class ServiceApi extends BaseApi {
  constructor() {
    super('/api/services')
  }

  // 获取服务类型列表（带缓存）
  async getServiceList() {
    try {
      return await this.getCached('', {}, 10 * 60 * 1000) // 缓存10分钟
    } catch (error) {
      throw this.handleError(error, { api: 'getServiceList' })
    }
  }

  // 获取服务详情
  async getServiceDetail(serviceId) {
    try {
      return await request.get(`/api/services/${serviceId}`)
    } catch (error) {
      throw this.handleError(error, { api: 'getServiceDetail', serviceId })
    }
  }

  // 获取服务价格
  async getServicePrice(serviceId, params = {}) {
    try {
      return await request.get(`/api/services/${serviceId}/price`, params)
    } catch (error) {
      throw this.handleError(error, { api: 'getServicePrice', serviceId, params })
    }
  }
}

export const serviceApi = new ServiceApi()

// 地址相关接口
export const addressApi = {
  // 获取地址列表
  async getAddressList() {
    try {
      return await request.get('/api/addresses')
    } catch (error) {
      throw errorHandler.handle(error, { api: 'getAddressList' })
    }
  },

  // 添加地址
  async addAddress(data) {
    try {
      // 参数验证
      if (!data.name || !data.phone || !data.detail) {
        throw new Error('地址信息不完整')
      }
      
      return await request.post('/api/addresses', data)
    } catch (error) {
      throw errorHandler.handle(error, { api: 'addAddress', data })
    }
  },

  // 更新地址
  async updateAddress(addressId, data) {
    try {
      return await request.put(`/api/addresses/${addressId}`, data)
    } catch (error) {
      throw errorHandler.handle(error, { api: 'updateAddress', addressId, data })
    }
  },

  // 删除地址
  async deleteAddress(addressId) {
    try {
      return await request.delete(`/api/addresses/${addressId}`)
    } catch (error) {
      throw errorHandler.handle(error, { api: 'deleteAddress', addressId })
    }
  },

  // 设置默认地址
  async setDefaultAddress(addressId) {
    try {
      return await request.put(`/api/addresses/${addressId}/default`)
    } catch (error) {
      throw errorHandler.handle(error, { api: 'setDefaultAddress', addressId })
    }
  }
}

// 优惠券相关接口
export const couponApi = {
  // 获取优惠券列表
  async getCouponList(params = {}) {
    try {
      return await request.get('/api/coupons', params)
    } catch (error) {
      throw errorHandler.handle(error, { api: 'getCouponList', params })
    }
  },

  // 领取优惠券
  async receiveCoupon(couponId) {
    try {
      return await request.post(`/api/coupons/${couponId}/receive`)
    } catch (error) {
      throw errorHandler.handle(error, { api: 'receiveCoupon', couponId })
    }
  },

  // 使用优惠券
  async useCoupon(couponId, orderId) {
    try {
      return await request.post(`/api/coupons/${couponId}/use`, { orderId })
    } catch (error) {
      throw errorHandler.handle(error, { api: 'useCoupon', couponId, orderId })
    }
  }
}

// 消息通知相关接口
export const notificationApi = {
  // 获取消息通知列表
  async getNotificationList(params = {}) {
    try {
      return await request.get('/api/notifications', params)
    } catch (error) {
      throw errorHandler.handle(error, { api: 'getNotificationList', params })
    }
  },

  // 标记消息为已读
  async markAsRead(notificationId) {
    try {
      return await request.put(`/api/notifications/${notificationId}/read`)
    } catch (error) {
      throw errorHandler.handle(error, { api: 'markAsRead', notificationId })
    }
  },

  // 批量标记为已读
  async markAllAsRead() {
    try {
      return await request.put('/api/notifications/read-all')
    } catch (error) {
      throw errorHandler.handle(error, { api: 'markAllAsRead' })
    }
  },

  // 删除通知
  async deleteNotification(notificationId) {
    try {
      return await request.delete(`/api/notifications/${notificationId}`)
    } catch (error) {
      throw errorHandler.handle(error, { api: 'deleteNotification', notificationId })
    }
  }
}

// 支付相关接口
export const paymentApi = {
  // 创建支付订单
  async createPayment(data) {
    try {
      if (!data.orderId || !data.amount) {
        throw new Error('支付信息不完整')
      }
      
      return await request.post('/api/payment/create', data)
    } catch (error) {
      throw errorHandler.handle(error, { api: 'createPayment', data })
    }
  },

  // 查询支付状态
  async getPaymentStatus(paymentId) {
    try {
      return await request.get(`/api/payment/${paymentId}/status`)
    } catch (error) {
      throw errorHandler.handle(error, { api: 'getPaymentStatus', paymentId })
    }
  },

  // 申请退款
  async requestRefund(orderId, reason) {
    try {
      return await request.post(`/api/payment/refund`, { orderId, reason })
    } catch (error) {
      throw errorHandler.handle(error, { api: 'requestRefund', orderId, reason })
    }
  }
}

// 文件上传接口
export const uploadApi = {
  // 上传图片
  async uploadImage(filePath, options = {}) {
    try {
      return await request.upload('/api/upload/image', filePath, {}, {
        name: 'image',
        ...options
      })
    } catch (error) {
      throw errorHandler.handle(error, { api: 'uploadImage', filePath })
    }
  },

  // 批量上传图片
  async uploadImages(filePaths, options = {}) {
    try {
      const uploadPromises = filePaths.map(filePath => 
        this.uploadImage(filePath, options)
      )
      return await Promise.all(uploadPromises)
    } catch (error) {
      throw errorHandler.handle(error, { api: 'uploadImages', filePaths })
    }
  }
}

// 统计相关接口
export const statisticsApi = {
  // 获取用户统计数据
  async getUserStatistics() {
    try {
      return await request.get('/api/statistics/user')
    } catch (error) {
      throw errorHandler.handle(error, { api: 'getUserStatistics' })
    }
  },

  // 获取订单统计数据
  async getOrderStatistics(params = {}) {
    try {
      return await request.get('/api/statistics/orders', params)
    } catch (error) {
      throw errorHandler.handle(error, { api: 'getOrderStatistics', params })
    }
  }
}

// 系统配置接口
export const configApi = {
  // 获取系统配置
  async getSystemConfig() {
    try {
      return await request.get('/api/config/system')
    } catch (error) {
      throw errorHandler.handle(error, { api: 'getSystemConfig' })
    }
  },

  // 获取版本信息
  async getVersionInfo() {
    try {
      return await request.get('/api/config/version')
    } catch (error) {
      throw errorHandler.handle(error, { api: 'getVersionInfo' })
    }
  }
}

// 导出所有API
export default {
  userApi,
  orderApi,
  serviceApi,
  addressApi,
  couponApi,
  notificationApi,
  paymentApi,
  uploadApi,
  statisticsApi,
  configApi
}